//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Modules.Admin.Modules
{
	partial class Export : Entities.Modules.PortalModuleBase
	{
		private new int ModuleId = -1;
		private ModuleInfo _Module;
		private ModuleInfo Module
		{
			get
			{
				if (_Module == null)
				{
					_Module = new ModuleController().GetModule(ModuleId, TabId, false);
				}
				return _Module;
			}
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			if (Request.QueryString["moduleid"] != null)
			{
				Int32.TryParse(Request.QueryString["moduleid"], out ModuleId);
			}
			if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", Module))
			{
				Response.Redirect(Common.Globals.AccessDeniedURL(), true);
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdExport.Click += new EventHandler(cmdExport_Click);

			try
			{
				if (Request.QueryString["moduleid"] != null)
				{
					Int32.TryParse(Request.QueryString["moduleid"], out ModuleId);
				}
				if (!Page.IsPostBack)
				{
					cboFolders.Items.Insert(0, new ListItem("<" + Services.Localization.Localization.GetString("None_Specified") + ">", "-"));
					ArrayList folders = FileSystemUtils.GetFoldersByUser(PortalId, false, false, "ADD");
					foreach (FolderInfo folder in folders)
					{
						ListItem FolderItem = new ListItem();
						if (folder.FolderPath == Null.NullString)
						{
							FolderItem.Text = Localization.GetString("Root", this.LocalResourceFile);
						}
						else
						{
                            FolderItem.Text = folder.DisplayPath;
						}
						FolderItem.Value = folder.FolderPath;
						cboFolders.Items.Add(FolderItem);
					}
					if (Module != null)
					{
						txtFile.Text = CleanName(Module.ModuleTitle);
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdCancel_Click(object sender, EventArgs e)
		{
			try
			{
				Response.Redirect(Common.Globals.NavigateURL(), true);
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdExport_Click(object sender, EventArgs e)
		{
			try
			{
				if (cboFolders.SelectedIndex != 0 && !String.IsNullOrEmpty(txtFile.Text))
				{
					string strFile = "content." + CleanName(Module.DesktopModule.ModuleName) + "." + CleanName(txtFile.Text) + ".xml";
					string strMessage = ExportModule(ModuleId, strFile, cboFolders.SelectedItem.Value);
					if (String.IsNullOrEmpty(strMessage))
					{
						Response.Redirect(Common.Globals.NavigateURL(), true);
					}
					else
					{
						UI.Skins.Skin.AddModuleMessage(this, strMessage, UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					}
				}
				else
				{
					UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private string ExportModule(int ModuleID, string FileName, string Folder)
		{
			string strMessage = "";
			if (Module != null)
			{
				if (!String.IsNullOrEmpty(Module.DesktopModule.BusinessControllerClass) && Module.DesktopModule.IsPortable)
				{
					try
					{
						object objObject = Framework.Reflection.CreateObject(Module.DesktopModule.BusinessControllerClass, Module.DesktopModule.BusinessControllerClass);
						if (objObject is IPortable)
						{
							string Content = Convert.ToString(((IPortable)objObject).ExportModule(ModuleID));
							if (!String.IsNullOrEmpty(Content))
							{
								Content = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<content type=\"" + CleanName(Module.DesktopModule.ModuleName) + "\" version=\"" + Module.DesktopModule.Version + "\">" + Content + "</content>";
								PortalController objPortalController = new PortalController();
								string strFile = PortalSettings.HomeDirectoryMapPath + Folder + FileName;
								if (objPortalController.HasSpaceAvailable(PortalId, Content.Length))
								{
									StreamWriter objStream;
									objStream = File.CreateText(strFile);
									objStream.WriteLine(Content);
									objStream.Close();
									FileSystemUtils.AddFile(FileName, PortalId, Folder, PortalSettings.HomeDirectoryMapPath, "application/octet-stream");
								}
								else
								{
									strMessage += "<br>" + string.Format(Localization.GetString("DiskSpaceExceeded"), strFile);
								}
							}
							else
							{
								strMessage = Localization.GetString("NoContent", this.LocalResourceFile);
							}
						}
						else
						{
							strMessage = Localization.GetString("ExportNotSupported", this.LocalResourceFile);
						}
					}
					catch
					{
						strMessage = Localization.GetString("Error", this.LocalResourceFile);
					}
				}
				else
				{
					strMessage = Localization.GetString("ExportNotSupported", this.LocalResourceFile);
				}
			}
			return strMessage;
		}
		private string CleanName(string Name)
		{
			string strName = Name;
			string strBadChars = ". ~`!@#$%^&*()-_+={[}]|\\:;<,>?/\"'";
			int intCounter;
			for (intCounter = 0; intCounter <= strBadChars.Length - 1; intCounter++)
			{
				strName = strName.Replace(strBadChars.Substring(intCounter, 1), "");
			}
			return strName;
		}
	}
}
